import neural_log
from config import platform
import pandas as pd
import json
from data.log_dir.query_log import export_log_data
from data.chaos_mesh_dir.query_chaos_mesh import export_chaos_mesh_data
import time


def get_params():
    import argparse

    # 创建解析器
    parser = argparse.ArgumentParser()

    # 添加参数
    parser.add_argument("--start_time", type=int)
    parser.add_argument("--end_time", type=int)

    # 解析参数
    args = parser.parse_args()

    # 返回参数
    return args.start_time, args.end_time


def train():
    processer = neural_log.Processer(platform)
    log_df = pd.read_csv("../dataset/origin_data/log/log.csv")
    anomaly_df = pd.read_csv(
        "../dataset/origin_data/groundtruth/ground_truth.csv"
    ).rename(columns={"起始时间戳": "st_time", "截止时间戳": "ed_time"})
    processer(log_df, anomaly_df)
    processer.train()


def test(log_df, anomaly_df):
    processer = neural_log.Processer(platform)
    processer(log_df, anomaly_df)
    return processer.test("./result/model.pth")


if __name__ == "__main__":
    data = {"status": "error", "result": {}}
    try:
        # 获取 start_time、end_time
        start_time, end_time = get_params()

        # 导出数据
        export_chaos_mesh_data(start_time, end_time)
        export_log_data(start_time, end_time)

        # # 读入数据
        log_df = pd.read_csv("./data/log.csv")
        anomaly_df = pd.read_csv("./data/ground_truth.csv").rename(
            columns={"起始时间戳": "st_time", "截止时间戳": "ed_time"}
        )

        # 训练模型
        # train()

        # 开始测试
        data["result"] = test(log_df, anomaly_df)

        # 写入结果
        data["status"] = "success"
    except Exception as e:
        print(e)
        data["status"] = "error"
        data["result"] = repr(e)
    finally:
        with open("./result/result.json", "w", encoding="utf-8") as f:
            json.dump(data, f)

        while 1:
            time.sleep(1)
